package io.github.mayubao.aidl.aidlclient;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import io.github.mayubao.aidl.aidlclinet.R;
import io.github.mayubao.aidl.aidlserver.IMyAidlInterface;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    IMyAidlInterface remoteService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onClick(View view){
        if(view.getId() == R.id.tv_bind){
            Log.i(TAG, "AIDLClient bind server***>>> click");
            Intent intent = new Intent();
            intent.setAction("io.github.mayubao.aidl.aidlserver.AIDLService");
            intent.setPackage("io.github.mayubao.aidl.aidlserver");
            bindService(intent, conn, Context.BIND_AUTO_CREATE);
        }else if(view.getId() == R.id.tv_unbind){
            Log.i(TAG, "AIDLClient unbind server***>>> click");
            unbindService(conn);
        }else if(view.getId() == R.id.tv_remote_call){
            if(null != remoteService){
                int anInt = 1;
                long aLong = 2l;
                boolean aBoolean = false;
                float aFloat    = 3.0f;
                double aDouble = 4.0d;
                String aString = "Hello world!";
                try {
                    remoteService.basicTypes(anInt, aLong, aBoolean, aFloat, aDouble, aString);
                } catch (RemoteException e) {
                    Log.i(TAG, "AIDLClient remote call have exception ***>>>" + e.getMessage());
                    e.printStackTrace();
                }
            }
        }

    }

    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(TAG, "AIDLClient onServiceConnected***>>>");
            remoteService = IMyAidlInterface.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG, "AIDLClient onServiceDisconnected***>>> click");
            remoteService = null;
        }
    };
}
